﻿using Nop.Core.Configuration;
using Nop.Core.Domain.Orders;
using Nop.Core.Domain.Payments;
using Nop.Services.Orders;
using Nop.Services.Tasks;
using System;
using System.Collections.Generic;
using Nop.Services.Logging;
using Nop.Core.Domain.Shipping;
using Nop.Web.Services.Factories;

namespace Nop.Web.Services.Task
{
    public class OrderShipmentTask : IScheduleTask
    {
        private readonly NopConfig _config;
        private readonly IOrderService _orderService;
        private readonly IOrderProcessingService _orderProcessingService;
        private readonly ILogger _logger;
        private readonly HUCFactory _hUCFactory;

        public OrderShipmentTask(ILogger logger, IOrderService orderService, IOrderProcessingService orderProcessingService, NopConfig config, HUCFactory hUCFactory)
        {
            _orderService = orderService;
            _orderProcessingService = orderProcessingService;
            _config = config;
            _logger = logger;
            _hUCFactory = hUCFactory;
        }


        public void Execute()
        {
            //DebugRun();
            //return;
            try
            {

                var orders = _orderService.SearchOrders(osIds: new List<int>() {
                        (int)OrderStatus.Processing
                    }, psIds: new List<int>() {
                         (int)PaymentStatus.Paid
                    }, ssIds: new List<int>() {
                         (int)ShippingStatus.Shipped
                    }, createdToUtc: DateTime.Now.ToUniversalTime().AddHours(_config.ShipProcessHours));
                foreach (var order in orders)
                {

                    foreach (var shipment in order.Shipments)
                    {
                        if (!shipment.DeliveryDateUtc.HasValue)
                        {
                            order.OrderNotes.Add(new OrderNote()
                            {
                                Note = $"用户包裹[{shipment.Id}]收货超时,已被设置为已收货状态",
                                DisplayToCustomer = true,
                                CreatedOnUtc = DateTime.UtcNow
                            });
                            _orderProcessingService.Deliver(shipment, true);
                        }
                    }
                    _hUCFactory.CalcOrderCount(order);
                }

            }
            catch (Exception ex)
            {
                _logger.Error($"执行订单确认收货发生错误", ex);
            }
        }


        void DebugRun()
        {
            var orders = _orderService.SearchOrders(osIds: new List<int>() {
                        (int)OrderStatus.Complete
                    });
            foreach (var order in orders)
            { 

                _hUCFactory.CalcOrderCount(order);
            }
        }
    }
}
